﻿namespace WebUI.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.Adapters;

    public class DropDownListAdapter : WebControlAdapter
    {
        protected override void RenderContents(HtmlTextWriter writer)
        {
            DropDownList list = base.Control as DropDownList;
            List<string> renderedOptionGroups = new List<string>();
            if (list != null)
            {
                foreach (ListItem item in list.Items)
                {
                    if (item.Attributes["OptionGroup"] == null)
                    {
                        RenderListItem(item, writer);
                    }
                    else
                    {
                        string currentOptionGroup = item.Attributes["OptionGroup"];
                        if (renderedOptionGroups.Contains(currentOptionGroup))
                        {
                            RenderListItem(item, writer);
                        }
                        else
                        {
                            if (renderedOptionGroups.Count > 0)
                            {
                                RenderOptionGroupEndTag(writer);
                            }
                            RenderOptionGroupBeginTag(currentOptionGroup, writer);
                            renderedOptionGroups.Add(currentOptionGroup);
                            RenderListItem(item, writer);
                        }
                    }
                }
            }
            if (renderedOptionGroups.Count > 0)
            {
                RenderOptionGroupEndTag(writer);
            }
        }

        private static void RenderListItem(ListItem item, HtmlTextWriter writer)
        {
            writer.WriteBeginTag("option");
            writer.WriteAttribute("value", item.Value, true);
            if (item.Selected)
            {
                writer.WriteAttribute("selected", "selected", false);
            }
            foreach (string key in item.Attributes.Keys)
            {
                writer.WriteAttribute(key, item.Attributes[key]);
            }
            writer.Write('>');
            HttpUtility.HtmlEncode(item.Text, writer);
            writer.WriteEndTag("option");
            writer.WriteLine();
        }

        private static void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)
        {
            writer.WriteBeginTag("optgroup");
            writer.WriteAttribute("label", name);
            writer.Write('>');
            writer.WriteLine();
        }

        private static void RenderOptionGroupEndTag(HtmlTextWriter writer)
        {
            writer.WriteEndTag("optgroup");
            writer.WriteLine();
        }
    }
}

